from django.shortcuts import render

# Create your views here.


# GET /areas/
from rest_framework.generics import GenericAPIView, ListAPIView, RetrieveAPIView
from rest_framework.mixins import ListModelMixin
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ReadOnlyModelViewSet
from rest_framework_extensions.cache.mixins import CacheResponseMixin

from areas.models import Area
from areas.serializers import AreaSerializer, SubAreaSerializer


class AreasViewSet(CacheResponseMixin, ReadOnlyModelViewSet):
    """
    行政区划信息
    """
    pagination_class = None  # 区划信息不分页

    def get_queryset(self):
        """
        提供数据集
        """
        if self.action == 'list':
            return Area.objects.filter(parent=None)
        else:
            return Area.objects.all()

    def get_serializer_class(self):
        """
        提供序列化器
        """
        if self.action == 'list':
            return AreaSerializer
        else:
            return SubAreaSerializer

class AreasView(ListAPIView):
    serializer_class = AreaSerializer
    queryset = Area.objects.filter(parent = None)
    # def get(self, request):
    #     """
    #     获取所有省的数据
    #     1. 从数据库查询出所有省的数据
    #     2. 将省的数据序列化并返回
    #     """
    #
    #     #1. 数据库查询所有省的数据
    #     areas = self.get_queryset()
    #
    #     #2. 将所有的数据序列化并返回
    #     serializer = self.get_serializer(areas, many=True)
    #     return Response(serializer.data)


# GET /areas/(?P<pk>\d+)/
class SubAreasView(RetrieveAPIView):
    serializer_class = SubAreaSerializer
    queryset = Area.objects.all()

    # def get(self, request, pk):
    #     """
    #     get_object(): 从视图所使用的查询集中获取指定的对象，默认根据pk进行查询
    #     获取指定地区的数据(在返回指定地区的数据时，将其下级地区嵌套返回):
    #     1. 根据pk获取指定地区的数据
    #     2. 将地区的数据序列化并返回(需要将地区关联的下级地区进行嵌套序列化)
    #     """
    #     # 1. 根据pk获取指定地区的数据
    #     area = self.get_object()
    #
    #     # 2. 将地区的数据序列化并返回
    #     serializer = self.get_serializer(area)
    #     return Response(serializer.data)